import React, { useEffect, useRef } from 'react';
import styles from './index.less';
import { Button, DatePicker, Drawer, Select, Space, Tooltip } from 'antd';
import moment from 'moment';

import { TRMessage } from '#/components';
import { FileTextOutlined, QuestionCircleOutlined, UploadOutlined } from '#/utils/antdIcons';
import { useTRState } from '#/utils/trHooks';
import { TjSegmented } from '@/pages/ETrade/components';

import MainComponents from './Main/index'; // 不同省份交易中心业务组件
import History from './History';

const getDateRange = (marketData) => {
  if (marketData.value === 'PDBLJ' || marketData.value === 'PXBNX') {
    return [moment().add(-3, 'day'), moment().add(1, 'day')];
  } else {
    return [moment().add(-3, 'day'), moment().add(3, 'day')];
  }
};

export default ({ power, buttonPermissions }) => {
  const mainRef = useRef(null);
  const [state, setState] = useTRState({
    formValue: null, // 记录使用过的表单
    stations: [],
    marketName: '',
    // 导出权限
    canExport: buttonPermissions.some((x) => x.menuCode === 'YunXinShuJuPiLuDaoChu'),
    // 长周期数据看板权限
    canLong: buttonPermissions.some((x) => x.menuCode === 'LongTermDataShowBoardButtonWeb'),
    // form
    market: power[0], // 交易中心信息
    openDates: null,
    dates: getDateRange(power[0]),
    type: '96',
    isRe: false,
  });

  useEffect(() => {
    _onFinish();
  }, []);

  const getAllStation = (data) => _.flattenDeep(data?.map((a) => a?.children));

  const _onFinish = () => {
    // 查询
    const formValue = {
      startDate: state.dates[0].format('YYYY-MM-DD'),
      endDate: state.dates[1].format('YYYY-MM-DD'),
      marketId: state.market.value,
      provinceId: state.market.provinceId,
      type: state.type,
    };

    const stations = getAllStation(state.market?.children || []);
    setState({
      formValue,
      stations,
      marketName: state.market.label,
    });
    setTimeout(() => {
      mainRef?.current?.onFetch?.();
    }, 0);
  };

  const _onReset = () => {
    // 重置
    setState({
      market: power[0], // 交易中心信息
      openDates: null,
      dates: getDateRange(power[0]),
      type: '96',
      showHistory: false,
      isRe: !state.isRe,
    });
    const formValue = {
      startDate: getDateRange(power[0])[0].format('YYYY-MM-DD'),
      endDate: getDateRange(power[0])[1].format('YYYY-MM-DD'),
      marketId: power[0].value,
      provinceId: power[0].provinceId,
      type: '96',
    };

    const stations = getAllStation(power[0]?.children || []);
    setState({
      formValue,
      stations,
      marketName: power[0].label,
    });
    setTimeout(() => {
      mainRef?.current?.onFetch?.();
    }, 0);
  };

  const disabledDate = (v) => {
    // 日期限制15天，不可选未来
    const _dates = state.openDates;
    if (!_dates) return false;
    const tooLate = _dates[0] && v.diff(_dates[0], 'days') > 14;
    const tooEarly = _dates[1] && _dates[1].diff(v, 'days') > 14;
    return !!tooEarly || !!tooLate;
  };

  const _onLook = () => {
    // 长周期数据看板
    if (!state.canLong) return TRMessage.info('请联系管理员获取相关权限');
    setState({ showHistory: true });
  };
  const _onExport = () => {
    // 导出
    if (!state.canExport) return TRMessage.info('请联系管理员获取相关权限');
    mainRef?.current?.onExport?.();
  };

  /** renders */
  const _renderMain = () => {
    // 不同省份业务拆分，根据交易中心编码匹配
    const { formValue, stations, marketName, isRe } = state;
    if (!formValue?.marketId) return null;
    const MainCompt = MainComponents?.[formValue.marketId] || MainComponents['PHBSX'];
    //const MainCompt = MainComponents?.['PHHLJ'];
    const mainProps = {
      formValue,
      stations,
      marketName,
      marketId: formValue.marketId,
      isRe: isRe,
    };
    return <MainCompt ref={mainRef} {...mainProps} />;
  };

  const changeMarket = (market) => {
    setState({
      market: market,
      dates: getDateRange(market),
    });
  };
  return (
    <div className={styles.cont}>
      <div className={styles.head}>
        <Space size={16} wrap>
          <Select
            style={{ width: 200 }}
            value={state.market.value}
            options={power}
            optionFilterProp="label"
            showSearch
            showArrow
            onChange={(v, market) => changeMarket(market)}
          />
          <div>
            <DatePicker.RangePicker
              style={{ width: 216 }}
              value={state.openDates || state.dates}
              separator="-"
              format={'YYYYMMDD'}
              disabledDate={disabledDate}
              allowClear={false}
              onChange={(dates) => setState({ dates })}
              onCalendarChange={(openDates) => setState({ openDates })}
              onOpenChange={(open) => setState({ openDates: open ? [null, null] : null })}
            />
            <Tooltip
              overlayClassName="overtoop"
              title={`当前页面最大支持查看15天数据${
                state.market.value !== 'PDBLJ' ? '，长周期数据请通过“长周期数据看板”查询！' : ''
              }`}
            >
              <QuestionCircleOutlined style={{ fontSize: 14, color: '#FD4F43', marginLeft: 8 }} />
            </Tooltip>
          </div>
          {state.market.value !== 'PXBGS' ? (
            <TjSegmented
              value={state.type}
              options={[
                { label: '24', value: '24' },
                { label: '96', value: '96' },
              ]}
              onChange={(type) => setState({ type })}
            />
          ) : (
            ''
          )}
          <Space size={16}>
            <Button
              style={{ width: 98, height: 32 }}
              type="primary"
              disabled={!state.dates || state.loading}
              onClick={_onFinish}
            >
              查询
            </Button>
            <Button style={{ width: 98, height: 32 }} ghost onClick={_onReset}>
              重置
            </Button>
          </Space>
        </Space>
        <Space>
          {state.market.value !== 'PDBLJ' && (
            <Button
              style={{ padding: 0 }}
              type="link"
              icon={<FileTextOutlined />}
              onClick={_onLook}
            >
              长周期数据看板
            </Button>
          )}
          <Button style={{ padding: 0 }} type="link" icon={<UploadOutlined />} onClick={_onExport}>
            导出
          </Button>
        </Space>
      </div>
      <div className={styles.main}>{_renderMain()}</div>
      <Drawer
        visible={state.showHistory}
        title={'长周期数据看板'}
        width={'96%'}
        placement={'right'}
        destroyOnClose={true}
        getContainer={false}
        onClose={() => setState({ showHistory: false })}
      >
        <History power={power} buttonPermissions={buttonPermissions} market={state.market} />
      </Drawer>
    </div>
  );
};
